package com.iot.manager.utils;

import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.lang.reflect.Method;

public class DeviceWifiManager {
    private static final String TAG = "DeviceWifiManager";
    private final WifiManager wifiManager;
    private final Context context;
    private final Handler mainHandler;
    private boolean isConnected = false;

    public interface ConnectionCallback {
        void onSuccess();
        void onError(String error);
    }

    public DeviceWifiManager(Context context) {
        this.context = context;
        this.wifiManager = (WifiManager) context.getApplicationContext()
                .getSystemService(Context.WIFI_SERVICE);
        this.mainHandler = new Handler(Looper.getMainLooper());
    }

    public boolean isConnected() {
        return isConnected;
    }

    public void connectToDeviceWifi(String ssid, String password, String deviceId, ConnectionCallback callback) {
        try {
            // 保存当前WiFi状态
            WifiManager wifiManager = (WifiManager) context.getApplicationContext()
                    .getSystemService(Context.WIFI_SERVICE);
            
            if (wifiManager == null) {
                callback.onError("无法获取WiFi服务");
                return;
            }

            // 配置设备WiFi
            WifiConfiguration wifiConfig = new WifiConfiguration();
            wifiConfig.SSID = String.format("\"%s\"", ssid);
            wifiConfig.preSharedKey = String.format("\"%s\"", password);
            wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
            wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
            wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);

            // 添加网络配置
            int netId = wifiManager.addNetwork(wifiConfig);
            wifiManager.disconnect();
            wifiManager.enableNetwork(netId, true);
            wifiManager.reconnect();

            // 设置连接状态
            isConnected = true;
            callback.onSuccess();
        } catch (Exception e) {
            isConnected = false;
            callback.onError("连接设备WiFi失败: " + e.getMessage());
        }
    }

    public void connectToDeviceHotspot(String ssid, String password, ConnectionCallback callback) {
        connectToDeviceWifi(ssid, password, null, callback);
    }

    public boolean isConnectedToWifi(String ssid) {
        if (wifiManager.getConnectionInfo() == null) {
            return false;
        }
        return wifiManager.getConnectionInfo().getSSID().equals("\"" + ssid + "\"");
    }

    public void disconnect() {
        try {
            WifiManager wifiManager = (WifiManager) context.getApplicationContext()
                    .getSystemService(Context.WIFI_SERVICE);
            if (wifiManager != null) {
                wifiManager.disconnect();
            }
            isConnected = false;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getCurrentWifiSSID() {
        if (wifiManager.getConnectionInfo() == null) {
            return null;
        }
        String ssid = wifiManager.getConnectionInfo().getSSID();
        return ssid != null ? ssid.replace("\"", "") : null;
    }

    public String getCurrentWifiPassword() {
        // 由于Android安全限制，无法直接获取已保存的WiFi密码
        // 这里返回null，实际使用时需要用户输入或从其他地方获取
        return null;
    }
} 